﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Nollie.Storage;
using System.Threading;
using Nollie.Utilities;
using Nollie.CacheTypes.Database;
using Nollie.CacheTypes.Memory;
using Nollie.CacheTypes.Mixed;
using Nollie.CacheTypes;

namespace Nollie
{
	public class CacheFactory
	{
		private static Dictionary<string, ICache> _caches = new Dictionary<string, ICache>();
		private static ReaderWriterLockSlim _locker = new ReaderWriterLockSlim();

		private static T GetCache<T>(string name, CacheConfiguration configuration)
			where T : ICache
		{
			using (var lockHelper = new ReaderLockHelper(_locker))
			{ 
				if (_caches.ContainsKey(name))
					 return (T) _caches[name];

			}

			using (var lockHelper = new WriterLockHelper(_locker))
			{
				ICache cache = default(T);

				if (typeof(T) == typeof(DbCache))
					cache = new DbCache(configuration);
				else if (typeof(T) == typeof(MemCache))
					cache = new MemCache();
				else if (typeof(T) == typeof(MixedCache))
					cache = new MixedCache(configuration);

				_caches.Add(name, cache);

				return (T) cache;
			}
		}

		public static IDbCache GetDbCache(string name, CacheConfiguration configuration)
		{
			return GetCache<DbCache>(name, configuration);
		}
		public static IMemCache GetMemCache(string name)
		{
			return GetCache<MemCache>(name, null);
		}
		public static IMixedCache GetMixedCache(string name, CacheConfiguration configuration)
		{
			return GetCache<MixedCache>(name, configuration);
		}
	}
}
